<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">个人空间后台系统</h3>
        <!-- 标题 -->
      </div>

      <!-- 用户名 -->
      <el-form-item prop="loginId">
        <span class="svg-container">
          <svg-icon icon-class="user" />
          <!-- 用户名的图标信息 -->
        </span>
        <el-input
          ref="loginId"
          v-model="loginForm.loginId"
          placeholder="请输入管理员账号"
          name="loginId"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <!-- 用户名提示框（警告） -->
      <div></div>

      <!-- 密码 -->
      <el-form-item prop="loginPwd">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.loginPwd"
          :type="passwordType"
          placeholder="请输入密码"
          name="loginPwd"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <!-- 密码的隐藏显示 切换 -->
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <!-- 验证码 -->
      <div class="captchaContainer">
        <el-form-item prop="captcha" class="captchaInp">
          <span class="svg-container">
            <svg-icon icon-class="user" />
            <!-- 验证码的图标信息 -->
          </span>
          <el-input
            ref=""
            v-model="loginForm.captcha"
            placeholder="请输入验证码"
            name="captcha"
            type="text"
            tabindex="3"
            auto-complete="on"
          />
        </el-form-item>
        <!-- 验证码图片 -->
        <div class="captchaImg" @click="captchaHandle()" v-html="svg"></div>
      </div>

      <div style="padding: 10px 0px">
        <!-- `checked` 为 true 或 false -->
        <el-checkbox v-model="loginForm.checked">7 天免登陆</el-checkbox>
      </div>

      <!-- 登录按钮 -->
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
//导入 验证码获取接口
import { getCaptchaImg } from "@/api/captcha.js";

export default {
  name: "Login",
  data() {
    // 判断用户名是否输入 如果没有输入 则显示对应警告
    const validateUsername = (rule, value, callback) => {
      console.log(value);
      if (!validUsername(value)) {
        callback(new Error("请输入用户名！"));
      } else {
        callback();
      }
    };
    // 判断密码是否输入 如果没有输入 则显示对应警告
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("请输入密码！"));
      } else {
        callback();
      }
    };

    // 判断验证码是否输入 如果没有输入 则显示对应警告
    const validateCaptcha = (rule, value, callback) => {
      //如果 value的长度为0 或者说value 的长度小于4 则警告请输入验证码 或者 请核对输入的验证码位数后重试
      //validate.js 中
      if (!value) {
        callback(new Error("请输入验证码"));
      } else if (value.length != 4) {
        callback(new Error("您输入的验证码位数有误，请核对后重试"));
      } else {
        callback();
      }
    };
    return {
      //svg 储存 验证码的svg 数据
      svg: "",
      // 储存 login 的账号密码数据
      loginForm: {
        loginId: "",
        loginPwd: "",
        captcha: "",
        // 用来表示是否 7 天内免登录
        checked: false,
      },

      loginRules: {
        loginId: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        loginPwd: [{ required: true, trigger: "blur", message: "请输入密码" }],
        captcha: [{ trigger: "blur", validator: validateCaptcha }],
      },
      // 加载动画的显示
      loading: false,
      // 密码的type
      passwordType: "password",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },

  created() {
    //一进来页面就给服务端发送请求 请求 验证码的图片
    this.captchaHandle();
    Message.success(
      "献给 Hgl，感谢她无论听到多少次“快写完了”都仍然坚定地支持我。"
    );
  },

  methods: {
    //向服务器发送请求 （请求内容为 请求登陆页面的二维码）
    captchaHandle() {
      getCaptchaImg().then((resolve) => {
        this.svg = resolve;
      });
    },

    //密码框的显示与隐藏按钮切换
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    // 点击登录按钮
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        //valid 是判断form表单是否通过验证 值为布尔值
        if (valid) {
          this.loading = true;
          //如果7天内免登陆打勾 那么就往loginForm中添加一个属性 rememberMe 值为 7
          if (this.loginForm.checked) {
            this.loginForm.rememberMe = 7;
          }
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
              this.loading = false;
              this.$message.success("登录成功");
              this.$message.success(
                "献给Hgl，感谢她们无论听到多少次“快写完了”都仍然坚定地支持我。"
              );
            })
            .catch((res) => {
              console.log(res);
              if (typeof res === "string") {
                // 验证码错误
                this.$message.error("验证码错误");
              } else {
                // 账号密码错误
                this.$message.error("账号密码错误");
              }
              this.loading = false;
              this.loginForm.captcha = "";
              this.captchaHandle();
            });
        } else {
          console.log("表单验证有错误");
          return false;
        }
      });
    },
  },
};
</script>

/*css样式开始*/
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.captchaContainer {
  display: flex;
  // justify-content: space-between;
}

.captchaInp {
  // width: 80%;
  width: 70%;
  height: 100%;
  height: 100%;
}

.captchaImg {
  width: 150px;
  height: 50px;
  cursor: pointer;
}
</style>
